//
//  OPHDownloadRequestExecute.m
//  AtWork2
//
//  Created by lingen on 4/25/16.
//  Copyright © 2016 Foreverht. All rights reserved.
//

#import "OPHDownloadRequestExecute.h"
#import <AFNetworking/AFNetworking.h>
#import "OPHDownloadRequest.h"
#import "OPHNetwork.h"

@interface OPHDownloadRequestExecute()

@property (nonatomic,strong) NSURLSessionDownloadTask* downloadTask;

@property (nonatomic,assign) UInt64 refreshMills;

@end

@implementation OPHDownloadRequestExecute


/**
 *  开始下载
 *
 *  @return 返回一个下载任务
 */
-(NSURLSessionDownloadTask*)startDownload{
     // AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
     
    NSURL *URL = [NSURL URLWithString:_downloadRequest.url];
    if (URL == nil) {
        URL = [NSURL URLWithString:[_downloadRequest.url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        if (URL) {
            _downloadRequest.url = [_downloadRequest.url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        }
    }
     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
     [request setValue:@"*/*" forHTTPHeaderField:@"Accept"];

     [request setTimeoutInterval:1000 * 60 * 60 * 24];
    
    __weak typeof(self) weakSelf = self;
    
    _downloadTask = [[OPHNetwork sharedInstance].sessionManager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
                                  if (weakSelf.progressBlock) {
                                       //控制下载时间通知的刷新频率
                                       double progress = downloadProgress.fractionCompleted;
                                       UInt64 current =  [[NSDate date] timeIntervalSince1970] * 1000;
                                       
                                       if (current - weakSelf.refreshMills > 500 || progress >= 1.0) {
                                            weakSelf.progressBlock(downloadProgress.fractionCompleted);
                                            weakSelf.refreshMills = current;
                                       }
                                  }
                             }
                          destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
                               NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
                              NSString* fileName = [response suggestedFilename];
                              if (weakSelf.downloadRequest.exceptedDownloadFilePath) {
                                  fileName = [NSString stringWithFormat:@"%@.%@",[NSUUID UUID].UUIDString,fileName.pathExtension];
                              }
                              return [documentsDirectoryURL URLByAppendingPathComponent:fileName];
                          }
                    completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
                         dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                              NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*) response;
                              NSString* contentType =  httpResponse.allHeaderFields[@"Content-Type"];
                             
                              if ([contentType rangeOfString:@"application/json"].location!=NSNotFound ||
                                  (httpResponse.statusCode < 200 || httpResponse.statusCode >= 300)) {
                                  
								  if (weakSelf.completeBlock) {
									  weakSelf.completeBlock(nil);
								  }
                              }else{
                                   if (!filePath) {
									   if (weakSelf.completeBlock) {
										   weakSelf.completeBlock(nil);
									   }
                                   }else{
                                        if (weakSelf.downloadRequest.exceptedDownloadFilePath) {
                                             NSError* error = nil;

                                             [[NSFileManager defaultManager] removeItemAtPath:weakSelf.downloadRequest.exceptedDownloadFilePath error:&error];
                                             [[NSFileManager defaultManager] moveItemAtPath:[filePath path] toPath:weakSelf.downloadRequest.exceptedDownloadFilePath error:&error];
                                            if (weakSelf.completeBlock) {
                                                weakSelf.completeBlock(weakSelf.downloadRequest.exceptedDownloadFilePath);
                                            }
                                        }else{
											if (weakSelf.completeBlock) {
												weakSelf.completeBlock([filePath absoluteString]);
											}
                                        }
                                   }
                              }
                         });

                         
                    }];
     
     [_downloadTask resume];
     
     return _downloadTask;
}


/**
 *  中止一个下载行为
 *
 *  @return 返回中止是否成功
 */
-(BOOL)cancelDownload{
    [_downloadTask cancel];
     return YES;
}

/*
 * 中断一个下载
 */
-(BOOL)pauseDownload{
     if (_downloadTask.state == NSURLSessionTaskStateRunning) {
          [_downloadTask suspend];
          return YES;
     }
     return NO;
}

/*
 * 恢复一个下载
 */
-(BOOL)resumeDownload{
     if (_downloadTask.state == NSURLSessionTaskStateSuspended) {
          [_downloadTask resume];
          return YES;
     }
     return NO;
}

@end
